Maps

Aula 19, M3

Carolina Musso

Sala de Situação - UnB

Esta semana

Aula 19 - Mapas

  • O que é GIS, como usar ggplot para Mapas …

  • Mapa do Brasil usando shapefiles salvos no computador..

Aula 29 - Dashboards

  • Uma breve introdução ao pacote flexdashboard

Leituras para aprofundamento

Termos importantes

  • Geographic Information System (GIS)

    • Gis e ArcGis
  • Vetor: Pontos, linhas e polígonos

  • Raster: Pixels

Como essas informações estão armazenadas?

  • Geralmente em Shapefiles

    • coleção de arquivos: .shp, .shx, and .dbf. ou mais…

    • Localização na superfície da terra

    • Sistema de coordenadas

Como importar isso para o R?

  • Pacotes, baixam direto os shapefiles

    • brazilmaps, geobr, naturalearth…
  • Ler de shapefiles no disco (seu computurador)

Atenção!

  • Não é um dataframe

  • Mas não importa, vamos fingir que é

Resumidamente

  1. Importar duas bases (seus dados e shapefiles)
  2. Fazer o join
  3. Fazer um mapa como se fosse um ggplot

Iniciando

Pacotes

rm(list=ls())  #limpa  o ambient
if (!require(pacman)) install.packages("pacman") #garante que tem o pacman
pacman::p_load(tidyverse, rio, sf, rnaturalearth, geobr, 
               lubridate, ggspatial, ggthemes, gsubfn) 

pacman::p_install_gh("yutannihilation/ggsflabel")

Mundo

Bases

# BANCOS DE CASOS----

#MUNDO
#banco bruto da OMS, como é baixado da internet, Casos Covid
who_bruto <- import("https://covid19.who.int/WHO-COVID-19-global-data.csv")


# SHAPEFILES ----

#MUNDO
mundo <- ne_countries(scale = "medium", returnclass = "sf") 
mundo
Simple feature collection with 241 features and 63 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -180 ymin: -89.99893 xmax: 180 ymax: 83.59961
Geodetic CRS:  +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
First 10 features:
  scalerank      featurecla labelrank           sovereignt sov_a3 adm0_dif
0         3 Admin-0 country         5          Netherlands    NL1        1
1         1 Admin-0 country         3          Afghanistan    AFG        0
2         1 Admin-0 country         3               Angola    AGO        0
3         1 Admin-0 country         6       United Kingdom    GB1        1
4         1 Admin-0 country         6              Albania    ALB        0
5         3 Admin-0 country         6              Finland    FI1        1
6         3 Admin-0 country         6              Andorra    AND        0
7         1 Admin-0 country         4 United Arab Emirates    ARE        0
8         1 Admin-0 country         2            Argentina    ARG        0
9         1 Admin-0 country         6              Armenia    ARM        0
  level              type                admin adm0_a3 geou_dif
0     2           Country                Aruba     ABW        0
1     2 Sovereign country          Afghanistan     AFG        0
2     2 Sovereign country               Angola     AGO        0
3     2        Dependency             Anguilla     AIA        0
4     2 Sovereign country              Albania     ALB        0
5     2           Country                Aland     ALD        0
6     2 Sovereign country              Andorra     AND        0
7     2 Sovereign country United Arab Emirates     ARE        0
8     2 Sovereign country            Argentina     ARG        0
9     2 Sovereign country              Armenia     ARM        0
               geounit gu_a3 su_dif              subunit su_a3 brk_diff
0                Aruba   ABW      0                Aruba   ABW        0
1          Afghanistan   AFG      0          Afghanistan   AFG        0
2               Angola   AGO      0               Angola   AGO        0
3             Anguilla   AIA      0             Anguilla   AIA        0
4              Albania   ALB      0              Albania   ALB        0
5                Aland   ALD      0                Aland   ALD        0
6              Andorra   AND      0              Andorra   AND        0
7 United Arab Emirates   ARE      0 United Arab Emirates   ARE        0
8            Argentina   ARG      0            Argentina   ARG        0
9              Armenia   ARM      0              Armenia   ARM        0
                  name            name_long brk_a3             brk_name
0                Aruba                Aruba    ABW                Aruba
1          Afghanistan          Afghanistan    AFG          Afghanistan
2               Angola               Angola    AGO               Angola
3             Anguilla             Anguilla    AIA             Anguilla
4              Albania              Albania    ALB              Albania
5                Aland        Aland Islands    ALD                Aland
6              Andorra              Andorra    AND              Andorra
7 United Arab Emirates United Arab Emirates    ARE United Arab Emirates
8            Argentina            Argentina    ARG            Argentina
9              Armenia              Armenia    ARM              Armenia
  brk_group abbrev postal                    formal_en formal_fr note_adm0
0      <NA>  Aruba     AW                        Aruba      <NA>     Neth.
1      <NA>   Afg.     AF Islamic State of Afghanistan      <NA>      <NA>
2      <NA>   Ang.     AO  People's Republic of Angola      <NA>      <NA>
3      <NA>   Ang.     AI                         <NA>      <NA>      U.K.
4      <NA>   Alb.     AL          Republic of Albania      <NA>      <NA>
5      <NA>  Aland     AI                Åland Islands      <NA>      Fin.
6      <NA>   And.    AND      Principality of Andorra      <NA>      <NA>
7      <NA> U.A.E.     AE         United Arab Emirates      <NA>      <NA>
8      <NA>   Arg.     AR           Argentine Republic      <NA>      <NA>
9      <NA>   Arm.    ARM          Republic of Armenia      <NA>      <NA>
  note_brk            name_sort name_alt mapcolor7 mapcolor8 mapcolor9
0     <NA>                Aruba     <NA>         4         2         2
1     <NA>          Afghanistan     <NA>         5         6         8
2     <NA>               Angola     <NA>         3         2         6
3     <NA>             Anguilla     <NA>         6         6         6
4     <NA>              Albania     <NA>         1         4         1
5     <NA>                Aland     <NA>         4         1         4
6     <NA>              Andorra     <NA>         1         4         1
7     <NA> United Arab Emirates     <NA>         2         1         3
8     <NA>            Argentina     <NA>         3         1         3
9     <NA>              Armenia     <NA>         3         1         2
  mapcolor13  pop_est gdp_md_est pop_year lastcensus gdp_year
0          9   103065     2258.0       NA       2010       NA
1          7 28400000    22270.0       NA       1979       NA
2          1 12799293   110300.0       NA       1970       NA
3          3    14436      108.9       NA         NA       NA
4          6  3639453    21810.0       NA       2001       NA
5          6    27153     1563.0       NA         NA       NA
6          8    83888     3660.0       NA       1989       NA
7          3  4798491   184300.0       NA       2010       NA
8         13 40913584   573900.0       NA       2010       NA
9         10  2967004    18770.0       NA       2001       NA
                     economy              income_grp wikipedia fips_10 iso_a2
0       6. Developing region 2. High income: nonOECD        NA    <NA>     AW
1  7. Least developed region           5. Low income        NA    <NA>     AF
2  7. Least developed region  3. Upper middle income        NA    <NA>     AO
3       6. Developing region  3. Upper middle income        NA    <NA>     AI
4       6. Developing region  4. Lower middle income        NA    <NA>     AL
5 2. Developed region: nonG7    1. High income: OECD        NA    <NA>     AX
6 2. Developed region: nonG7 2. High income: nonOECD        NA    <NA>     AD
7       6. Developing region 2. High income: nonOECD        NA    <NA>     AE
8    5. Emerging region: G20  3. Upper middle income        NA    <NA>     AR
9       6. Developing region  4. Lower middle income        NA    <NA>     AM
  iso_a3 iso_n3 un_a3 wb_a2 wb_a3 woe_id adm0_a3_is adm0_a3_us adm0_a3_un
0    ABW    533   533    AW   ABW     NA        ABW        ABW         NA
1    AFG    004   004    AF   AFG     NA        AFG        AFG         NA
2    AGO    024   024    AO   AGO     NA        AGO        AGO         NA
3    AIA    660   660  <NA>  <NA>     NA        AIA        AIA         NA
4    ALB    008   008    AL   ALB     NA        ALB        ALB         NA
5    ALA    248   248  <NA>  <NA>     NA        ALA        ALD         NA
6    AND    020   020    AD   ADO     NA        AND        AND         NA
7    ARE    784   784    AE   ARE     NA        ARE        ARE         NA
8    ARG    032   032    AR   ARG     NA        ARG        ARG         NA
9    ARM    051   051    AM   ARM     NA        ARM        ARM         NA
  adm0_a3_wb     continent region_un       subregion                  region_wb
0         NA North America  Americas       Caribbean  Latin America & Caribbean
1         NA          Asia      Asia   Southern Asia                 South Asia
2         NA        Africa    Africa   Middle Africa         Sub-Saharan Africa
3         NA North America  Americas       Caribbean  Latin America & Caribbean
4         NA        Europe    Europe Southern Europe      Europe & Central Asia
5         NA        Europe    Europe Northern Europe      Europe & Central Asia
6         NA        Europe    Europe Southern Europe      Europe & Central Asia
7         NA          Asia      Asia    Western Asia Middle East & North Africa
8         NA South America  Americas   South America  Latin America & Caribbean
9         NA          Asia      Asia    Western Asia      Europe & Central Asia
  name_len long_len abbrev_len tiny homepart                       geometry
0        5        5          5    4       NA MULTIPOLYGON (((-69.89912 1...
1       11       11          4   NA        1 MULTIPOLYGON (((74.89131 37...
2        6        6          4   NA        1 MULTIPOLYGON (((14.19082 -5...
3        8        8          4   NA       NA MULTIPOLYGON (((-63.00122 1...
4        7        7          4   NA        1 MULTIPOLYGON (((20.06396 42...
5        5       13          5    5       NA MULTIPOLYGON (((20.61133 60...
6        7        7          4    5        1 MULTIPOLYGON (((1.706055 42...
7       20       20          6   NA        1 MULTIPOLYGON (((53.92783 24...
8        9        9          4   NA        1 MULTIPOLYGON (((-64.54917 -...
9        7        7          4   NA        1 MULTIPOLYGON (((45.55234 40...

Preparando as bases

# MANIPULAÇÕES NO BANCO -----------

# OMS
who_trat <- who_bruto %>% 
  dplyr::select(WHO_region,Date_reported,Country,New_cases,Cumulative_cases, New_deaths)%>% 
  dplyr::group_by(WHO_region, Country) %>% # agrupando  (tabela dinamica)
  dplyr::summarise(Acumulado=max(Cumulative_cases, na.rm=T)) 

# Shape
mundo_trat <- mundo %>% 
  dplyr::rename(Country=admin) # PARA PODER FAZER O JOIN

Join

covid_mundo_com_shape <- left_join(who_trat,  mundo_trat)
  • Vamos plotar?

Mas antes!

Vamos dar olhada num papa genérico.

ggplot(mundo)+
  geom_sf(aes(geometry=geometry))

  • Duas linhas!

Com nossos dados

ggplot(covid_mundo_com_shape,aes(geometry=geometry))+
  geom_sf(aes(fill=Acumulado ))+
  scale_fill_distiller(direction=1)+
  theme_map()

Uma melhoradinha nos números

eixo = function(x) format(x, big.mark = ".",
                          decimal.mark = ",",
                          scientific = FALSE)

ggplot(covid_mundo_com_shape,aes(geometry=geometry))+
  geom_sf(aes(fill=Acumulado ))+
  scale_fill_distiller(direction=1, label=eixo)+
  theme_map()

Notaram um probleminha?

  • Mundo:

    • Trabalhar códigos ISO
    • Ter um dicionário (e fazer um join)
mundo_iso <- mundo_trat %>% 
  dplyr::rename(iso=iso_a2)

who_acumulado_iso <- who_bruto %>% 
  dplyr::group_by(Country_code) %>% #iso
  dplyr::summarise(Acumulado=max(Cumulative_cases, na.rm=T)) %>% 
  rename(iso=Country_code)

covid_mundo_com_shape_iso <- left_join(who_acumulado_iso, mundo_iso)

Firulas

covid_mundo_com_shape_iso2<- covid_mundo_com_shape_iso %>% 
  mutate(Acumulado_cat=cut(Acumulado,
                           breaks=c(-1,17000,160000,1000000,
                                    max(covid_mundo_com_shape_iso$Acumulado, na.rm=T)+1),
                           labels=c("até 17 mil", "17 mil - 160 mil ", 
                                    "160 mil - 1 milhão", "acima de 1 milhão")))


paleta<-c('#feebe2','#fbb4b9','#f768a1','#ae017e')
ggplot(covid_mundo_com_shape_iso2, fill="white")+
  geom_sf(aes(geometry=geometry, fill=Acumulado_cat ), 
          color="purple", # cor da fronteira
              lwd=0.1) + # finura da fronteira
  scale_fill_manual(values=paleta, name="Casos Acumulados \n de covid-19  no Mundo")+
  theme_map()+
 theme(panel.background = element_rect(fill = "lightblue"),
       legend.position = "bottom")+
  ggtitle("Um mapa bonito")#oceano

ggsave("mapa_rosa.png")

Brasil

Preparação

rm(list=ls())  #limpa  o ambient
if (!require(pacman)) install.packages("pacman") #garante que tem o pacman
pacman::p_load(tidyverse, rio, sf, rnaturalearth,  geobr,
               lubridate, ggspatial, ggthemes, gsubfn, ggsn) 

pacman::p_load_gh("yutannihilation/ggsflabel")

Bases

Outra forma de ler shapefiles

brasil_bruto <- import("Exercicios/covid_br_2022.csv")

estados <- read_sf(dsn = "Exercicios/shapefiles/.",
                  layer="UFBR")

# tratando os dados
brasil_acumulado_estado <- brasil_bruto %>% 
  filter(municipio!="")%>% 
  group_by(estado) %>% 
  summarise(Acumulado=sum(casosNovos, na.rm=T))

estados_trat <- estados %>% 
  rename(estado=SIGLA) %>% 
  st_zm() # as vezes  precisa, nem sempre

covid_brasil_com_shape <- left_join(brasil_acumulado_estado, estados_trat)

Brasil

ggplot(estados_trat)+
  geom_sf(aes(geometry=geometry)) 

ggplot(covid_brasil_com_shape)+
  geom_sf(aes(geometry=geometry, fill=Acumulado))

Graficos de pontos

  • Usando st_centroid()
covid_brasil_com_shape_ponto <- covid_brasil_com_shape %>% 
  mutate(centro=st_centroid(geometry))

ggplot(covid_brasil_com_shape_ponto)+
  geom_sf(aes(geometry=geometry))+
  geom_sf(aes(geometry=centro, size=Acumulado), color="red", alpha=0.5)

  • Ou usar geom_point com x=lat e y=long

Outras formas …

geoBr

head(list_geobr())
                    function           geography
1             `read_country`             Country
2              `read_region`              Region
3               `read_state`              States
4         `read_meso_region`         Meso region
5        `read_micro_region`        Micro region
6 `read_intermediate_region` Intermediate region
                                                                                                                               years
1 1872, 1900, 1911, 1920, 1933, 1940, 1950, 1960, 1970, 1980, 1991, 2000, 2001, 2010, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
2                                                                   2000, 2001, 2010, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
3 1872, 1900, 1911, 1920, 1933, 1940, 1950, 1960, 1970, 1980, 1991, 2000, 2001, 2010, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
4                                                                   2000, 2001, 2010, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
5                                                                   2000, 2001, 2010, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
6                                                                                                                   2017, 2019, 2020
  source
1   IBGE
2   IBGE
3   IBGE
4   IBGE
5   IBGE
6   IBGE
regiao_geobr <- read_region() %>% 
  rename(regiao=`name_region`) %>% 
  mutate(regiao=if_else(regiao=="Centro Oeste", "Centro-Oeste", regiao))

Downloading: 1.8 kB     
Downloading: 1.8 kB     
Downloading: 5.1 kB     
Downloading: 5.1 kB     
Downloading: 37 kB     
Downloading: 37 kB     
Downloading: 46 kB     
Downloading: 46 kB     
Downloading: 78 kB     
Downloading: 78 kB     
Downloading: 220 kB     
Downloading: 220 kB     
Downloading: 260 kB     
Downloading: 260 kB     
Downloading: 280 kB     
Downloading: 280 kB     
Downloading: 380 kB     
Downloading: 380 kB     
Downloading: 390 kB     
Downloading: 390 kB     
Downloading: 390 kB     
Downloading: 390 kB     
Downloading: 420 kB     
Downloading: 420 kB     
Downloading: 420 kB     
Downloading: 420 kB     
Downloading: 450 kB     
Downloading: 450 kB     
Downloading: 520 kB     
Downloading: 520 kB     
Downloading: 550 kB     
Downloading: 550 kB     
Downloading: 630 kB     
Downloading: 630 kB     
Downloading: 630 kB     
Downloading: 630 kB     
Downloading: 660 kB     
Downloading: 660 kB     
Downloading: 690 kB     
Downloading: 690 kB     
Downloading: 720 kB     
Downloading: 720 kB     
Downloading: 730 kB     
Downloading: 730 kB     
Downloading: 730 kB     
Downloading: 730 kB     
Downloading: 780 kB     
Downloading: 780 kB     
Downloading: 780 kB     
Downloading: 780 kB     
brasil_regiao <- brasil_bruto %>% 
  filter(codmun != "") %>% 
  group_by(regiao) %>% 
  summarise(Maximo_dia=max(casosNovos, na.rm=T)) %>% 
  right_join(regiao_geobr)
ggplot(brasil_regiao, aes(fill=Maximo_dia))+
  geom_sf(aes(geometry=geom))+
  scale_fill_distiller(direction=1)

DF

funcao_limpeza<-function(x){
  limpeza_acentos <- list('Š'='S', 'š'='s', 'Ž'='Z', 'ž'='z', 'À'='A', 'Á'='A', 'Â'='A', 'Ã'='A', 'Ä'='A', 'Å'='A', 'Æ'='A', 'Ç'='C', 'È'='E', 'É'='E','Ê'='E', 'Ë'='E', 'Ì'='I', 'Í'='I', 'Î'='I', 'Ï'='I', 'Ñ'='N', 'Ò'='O', 'Ó'='O', 'Ô'='O', 'Õ'='O', 'Ö'='O', 'Ø'='O', 'Ù'='U','Ú'='U', 'Û'='U', 'Ü'='U', 'Ý'='Y', 'Þ'='B', 'ß'='Ss' )
  gsubfn(paste(names(limpeza_acentos),collapse='|'), limpeza_acentos,x)}

ras_df <- read_sf( dsn = "Exercicios/shapefiles/.",
                  layer="Regioes_Administrativas")%>% 
  mutate(RA=funcao_limpeza(ra)) 

Obrigada!